package jxc.servlet.user;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxc.base.helper.Encrypt;
import jxc.base.helper.UserAuthenticator;
import jxc.data.hibernate.dao.OperatorDAO;
import jxc.data.hibernate.pojo.Operator;

/**
 * Servlet implementation class AlertSelf
 */
@WebServlet("/user/alertUser")
public class Alert extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	/**
	 * get方法 获取用户,返回更改界面
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("username");
		OperatorDAO opDao=new OperatorDAO();
		Operator user=opDao.getByUsername(username);
		if(user==null){
			response.sendRedirect("listUser");
			return;
		}
		if(UserAuthenticator.getUser(request).getUsername().equals(user.getUsername())){
			response.sendRedirect("passwd");
			return;
		}
		request.setAttribute("user", user);
		request.getRequestDispatcher("/user/alertUser.jsp").forward(request, response);
	}

	/**
	 * post方法,修改当前用户
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("user");
		if(UserAuthenticator.getUser(request).getUsername().equals(username)){
			response.sendRedirect("passwd");
			return;
		}
		Operator user=new OperatorDAO().getByUsername(username);
		String name=request.getParameter("name");
		String password=request.getParameter("password");
		user.setName(name);
		//检测密码长度
		if(password.length()<6){
			request.setAttribute("message", "密码至少六位");
			request.setAttribute("user", user);
			request.getRequestDispatcher("/user/alertUser.jsp").forward(request, response);
			return;
		}
		user.setPassword(Encrypt.md5(password));
		OperatorDAO opDAO=new OperatorDAO();
		opDAO.update(user);
		opDAO.commit();
		request.setAttribute("message", "修改成功");
		request.setAttribute("user", user);
		request.getRequestDispatcher("/user/alertUser.jsp").forward(request, response);
	}

}
